package com.example.order.service.impl;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.example.order.bean.Order;
import com.example.order.feign.ProductFeignClient;
import com.example.order.service.OrderService;
import com.example.product.bean.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    DiscoveryClient discoveryClient;
    @Autowired
    RestTemplate restTemplate;
    @Autowired  // 一定导入spring-cloud-starter-loadbalancer，否则报错
    LoadBalancerClient loadBalancerClient;
    @Autowired
    ProductFeignClient productFeignClient;

    /**
     * 创建订单
     *
     * @param productId
     * @param userId
     * @return
     */
    @SentinelResource(value = "createOrder", blockHandler = "createOrderFallback")
    @Override
    public Order createOrder(Long productId, Long userId) {
//        Product product = getProductFromRemoteWithLoadBalanceAnnotation(productId);
        Product product = productFeignClient.getProductById(productId);
        Order order = new Order();

        order.setId(1L);
        //  商品总金额
        order.setTotalAmount(product.getPrice().multiply(new BigDecimal(product.getNum())));
        order.setUserId(userId);
        order.setNickName("张三");
        order.setAddress("北华北");
        //  远程查询商品列表
        order.setProductList(Arrays.asList(product));
        return order;
    }

    // 兜底回调
    public Order createOrderFallback(Long productId, Long userId, BlockException e) {
        Order order = new Order();
        order.setId(0L);
        order.setTotalAmount(new BigDecimal("0"));
        order.setUserId(userId);
        order.setNickName("为止用户");
        order.setAddress("异常信息：" + e.getClass());

        return order;
    }

    private Product getProductFromRemote(Long productId) {
        // 1.获取到商品服务所在的所有机器ip+port
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        ServiceInstance serviceInstance = instances.get(0);
        // 2.根据ip+port获取到商品服务 http://localhost:9003/product/4
        String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/product/" + productId;
        log.info("远程请求路径：{}" + url);
        // 3.发送http请求，获取到商品信息
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }

    // 进阶二 负载均衡发送请求
    private Product getProductFromRemoteWithLoadBalance(Long productId) {
        // 1.获取到商品服务所在的所有机器ip+port
        ServiceInstance choose = loadBalancerClient.choose("service-product");
        // 2.根据ip+port获取到商品服务 http://localhost:9003/product/4
        String url = "http://" + choose.getHost() + ":" + choose.getPort() + "/product/" + productId;
        log.info("远程请求路径：{}" + url);
        // 3.发送http请求，获取到商品信息
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }

    // 进阶三 基于注解的负载均衡发送请求
    private Product getProductFromRemoteWithLoadBalanceAnnotation(Long productId) {
        String url = "http://service-product/product/" + productId;
        // 3.发送http请求，获取到商品信息   service-product会被动态替换
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }
}
